﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBinder.Host.Infrastructures.ModelBinders;

public class CustomMultiModelBinderProvider : IModelBinderProvider
{
    private readonly MvcOptions _options;

    public CustomMultiModelBinderProvider(MvcOptions options)
    {
        _options = options;
    }

    public IModelBinder? GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var logger = context.Services.GetService<ILogger<CustomMultiModelBinderProvider>>();
        logger.LogInformation($"{context.Metadata.ModelType.Name} {context.Metadata.Name}");

        if (context.BindingInfo.BindingSource != null && context.BindingInfo.BindingSource.CanAcceptDataFrom(FromCustomMultiAttribute.CustomMulti))
        {
            var bodyModelBinderProvider = _options.ModelBinderProviders.OfType<BodyModelBinderProvider>().FirstOrDefault()!;
            var complexObjectModelBinderProvider = _options.ModelBinderProviders.OfType<ComplexObjectModelBinderProvider>().FirstOrDefault()!;

            var bodyModelBinder = bodyModelBinderProvider.GetBinder(context);
            var complexObjectModelBinder = complexObjectModelBinderProvider.GetBinder(context);
            return new CustomMultiModelBinder((BodyModelBinder)bodyModelBinder, (ComplexObjectModelBinder)complexObjectModelBinder);
        }

        return null;
    }
}